package app.sceledroid.filechooser;

//taken from http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import app.sceledroid.R;
import app.sceledroid.activity.course.ResourceActivity;
import app.sceledroid.entity.Deadline;
import app.sceledroid.services.SceleService;
import app.sceledroid.services.SceleService.SceleBinder;

public class FileChooser extends ListActivity {
	
    private File currentDir;
    private FileArrayAdapter adapter;
    private String url="";
    private Deadline d;
    
    private SceleService sceleService;
	private boolean isBounded;
    
	private ServiceConnection sceleServiceConnection = new ServiceConnection() {

		//@Override
		public void onServiceConnected(ComponentName componentName,
				IBinder iBinder) {
			// TODO Auto-generated method stub
			SceleBinder binder = (SceleBinder) iBinder;
			sceleService = binder.getService();
			isBounded = true;
		}

		//@Override
		public void onServiceDisconnected(ComponentName componentName) {
			// TODO Auto-generated method stub
			isBounded = false;
		}

	};
	
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentDir = new File("/sdcard/");
        Bundle bundle = this.getIntent().getExtras();
        String name = bundle.getString("dname");
        String url = bundle.getString("durl");
        String dstart = bundle.getString("dstart");
        String dend =  bundle.getString("dend");
        String info = bundle.getString("dinfo");
        d = new Deadline(name, new Date(dstart), new Date(dend), url, info);
        fill(currentDir);
    }
    private void fill(File f)
    {
    	File[]dirs = f.listFiles();
		 this.setTitle("Current Dir: "+f.getName());
		 List<Option>dir = new ArrayList<Option>();
		 List<Option>fls = new ArrayList<Option>();
		 try{
			 for(File ff: dirs)
			 {
				if(ff.isDirectory())
					dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
				else
				{
					fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
				}
			 }
		 }catch(Exception e)
		 {
			 
		 }
		 Collections.sort(dir);
		 Collections.sort(fls);
		 dir.addAll(fls);
		 if(!f.getName().equalsIgnoreCase("sdcard"))
			 dir.add(0,new Option("..","Parent Directory",f.getParent()));
		 adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir);
		 this.setListAdapter(adapter);
    }
    @Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Option o = adapter.getItem(position);
		if(o.getData().equalsIgnoreCase("folder")||o.getData().equalsIgnoreCase("parent directory")){
				currentDir = new File(o.getPath());
				fill(currentDir);
		}
		else
		{
			onFileClick(o);
		}
	}
    private void onFileClick(Option o)
    {
    	Toast.makeText(this, "File Clicked: "+o.getName()+":"+url, Toast.LENGTH_SHORT).show();
    	if(sceleService.uploadFile(this, d, o.getPath())){
			Toast.makeText(this, "SUCCED", Toast.LENGTH_LONG).show();
		}
    	//String a[] = d.getUrl().split("=");
    	//check(o.getPath(), a[0]);
    	//Toast.makeText(this, "FINISHED", Toast.LENGTH_SHORT).show();
    }
    
    public void check(String path, String id)
    {
    	DefaultHttpClient client = new DefaultHttpClient();


		HttpPost request = new HttpPost("http://scele.cs.ui.ac.id/login/index.php");
		HttpGet request1 = new HttpGet("http://scele.cs.ui.ac.id/login/index.php");
		List<NameValuePair> requestPair = new ArrayList<NameValuePair>();
		System.out.println("name :\n");
		try {

			HttpResponse response = client.execute(request1);

			InputStream stream = response.getEntity().getContent();
			List<Cookie> cStore = client.getCookieStore().getCookies();

			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			reader.close();
			reader = new BufferedReader(new InputStreamReader(System.in));

			for (Cookie c : cStore) {
				System.out.println("Cookie : " +  c.getName() + c.getValue());
			}
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
			String username = pref.getString("username", "");
			String passwd = pref.getString("password", "");
			requestPair.add(new BasicNameValuePair("username", username));

			System.out.println("\npassword :\n");
			requestPair.add(new BasicNameValuePair("password", passwd));
			request.setEntity(new UrlEncodedFormEntity(requestPair, HTTP.UTF_8));
			response = client.execute(request);

			cStore = client.getCookieStore().getCookies();

			for (Cookie c : cStore) {
				System.out.println("Cookie : " +  c.getName() + c.getValue());
			}
			stream = response.getEntity().getContent();
			reader = new BufferedReader(new InputStreamReader(stream));
			reader.close();
			//int id = 25970;
			File file = new File(path);
			MultipartEntity datas = new MultipartEntity();
		    ContentBody fileStream = new FileBody(file);
		    datas.addPart("newfile",fileStream);
		    datas.addPart("id", new StringBody(id));
		    datas.addPart("MAX_FILE_SIZE", new StringBody("2097152"));
		    datas.addPart("save", new StringBody("Upload this file"));
		    
		    
		    request = new HttpPost("http://scele.cs.ui.ac.id/mod/assignment/upload.php");
		    request.setEntity(datas);
		    response = client.execute(request);
		    stream = response.getEntity().getContent();
		    
			reader = new BufferedReader(new InputStreamReader(stream));
			String line;
			FileWriter writer = new FileWriter("/sdcard/report.txt");
			while(( line = reader.readLine()) != null){
				writer.append(line);
				
			}
			writer.flush();
			writer.close();
		     	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    @Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		bindToService();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	private void bindToService() {
		Intent service = new Intent(this, SceleService.class);
		this.bindService(service, sceleServiceConnection, Context.BIND_AUTO_CREATE);
	}
}